{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wJcYs_ERTnnI"
      },
      "source": [
        "##### Copyright 2021 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "HMUDt0CiUJk9"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "77z2OchJTk0l"
      },
      "source": [
        "# Migrate evaluation\n",
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/guide/migrate/evaluator\">\n",
        "    <img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />\n",
        "    View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/migrate/evaluator.ipynb\">\n",
        "    <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />\n",
        "    Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/evaluator.ipynb\">\n",
        "    <img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />\n",
        "    View source on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/migrate/evaluator.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "n4O6fPyYTxZv"
      },
      "source": [
        "Evaluation is a critical part of measuring and benchmarking models.\n",
        "\n",
        "This guide demonstrates how to migrate evaluator tasks from TensorFlow 1 to  TensorFlow 2. In Tensorflow 1  this functionality is implemented by `tf.estimator.train_and_evaluate`, when the API is running distributedly. In Tensorflow 2, you can use the built-in `tf.keras.utils.SidecarEvaluator`, or a custom evaluation loop on the evaluator task.\n",
        "\n",
        "There are simple serial evaluation options in both TensorFlow 1 (`tf.estimator.Estimator.evaluate`) and TensorFlow 2 (`Model.fit(..., validation_data=(...))` or `Model.evaluate`). The evaluator task is preferable when you would like your workers not switching between training and evaluation, and built-in evaluation in `Model.fit` is preferable when you would like your evaluation to be distributed.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pHJfmkCFUhQf"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "VXnPvQi8Ui1F"
      },
      "outputs": [],
      "source": [
        "import tensorflow.compat.v1 as tf1\n",
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "import tempfile\n",
        "import time\n",
        "import os"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Tww-uIoiUlsT"
      },
      "outputs": [],
      "source": [
        "mnist = tf.keras.datasets.mnist\n",
        "\n",
        "(x_train, y_train),(x_test, y_test) = mnist.load_data()\n",
        "x_train, x_test = x_train / 255.0, x_test / 255.0"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TtlucRG_Uro_"
      },
      "source": [
        "## TensorFlow 1: Evaluating using tf.estimator.train_and_evaluate\n",
        "\n",
        "In TensorFlow 1, you can configure a `tf.estimator` to evaluate the estimator using `tf.estimator.train_and_evaluate`.\n",
        "\n",
        "In this example, start by defining the `tf.estimator.Estimator` and speciyfing training and evaluation specifications:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Q8shCkV2jKcc"
      },
      "outputs": [],
      "source": [
        "feature_columns = [tf1.feature_column.numeric_column(\"x\", shape=[28, 28])]\n",
        "\n",
        "classifier = tf1.estimator.DNNClassifier(\n",
        "    feature_columns=feature_columns,\n",
        "    hidden_units=[256, 32],\n",
        "    optimizer=tf1.train.AdamOptimizer(0.001),\n",
        "    n_classes=10,\n",
        "    dropout=0.2\n",
        ")\n",
        "\n",
        "train_input_fn = tf1.estimator.inputs.numpy_input_fn(\n",
        "    x={\"x\": x_train},\n",
        "    y=y_train.astype(np.int32),\n",
        "    num_epochs=10,\n",
        "    batch_size=50,\n",
        "    shuffle=True,\n",
        ")\n",
        "\n",
        "test_input_fn = tf1.estimator.inputs.numpy_input_fn(\n",
        "    x={\"x\": x_test},\n",
        "    y=y_test.astype(np.int32),\n",
        "    num_epochs=10,\n",
        "    shuffle=False\n",
        ")\n",
        "\n",
        "train_spec = tf1.estimator.TrainSpec(input_fn=train_input_fn, max_steps=10)\n",
        "eval_spec = tf1.estimator.EvalSpec(input_fn=test_input_fn,\n",
        "                                   steps=10,\n",
        "                                   throttle_secs=0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sGP7Nyenk1gr"
      },
      "source": [
        "Then, train and evaluate the model. The evaluation runs synchronously between training because it's limited as a local run in this notebook and alternates between training and evaluation. However, if the estimator is used distributedly, the evaluator will run as a dedicated evaluator task. For more information, check the [migration guide on distributed training](https://www.tensorflow.org/guide/migrate/multi_worker_cpu_gpu_training)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xWKMsmt6jYSL"
      },
      "outputs": [],
      "source": [
        "tf1.estimator.train_and_evaluate(estimator=classifier,\n",
        "                                train_spec=train_spec,\n",
        "                                eval_spec=eval_spec)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "T5LtVtmvYx7J"
      },
      "source": [
        "## TensorFlow 2: Evaluating a Keras model\n",
        "\n",
        "In TensorFlow 2, if you use the Keras `Model.fit` API for training, you can evaluate the model with `tf.keras.utils.SidecarEvaluator`. You can also visualize the evaluation metrics in TensorBoard which is not shown in this guide.\n",
        "\n",
        "To help demonstrate this, let's first start by defining and training the model:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Ci3yB6A5lwJu"
      },
      "outputs": [],
      "source": [
        "def create_model():\n",
        "  return tf.keras.models.Sequential([\n",
        "    tf.keras.layers.Flatten(input_shape=(28, 28)),\n",
        "    tf.keras.layers.Dense(512, activation='relu'),\n",
        "    tf.keras.layers.Dropout(0.2),\n",
        "    tf.keras.layers.Dense(10)\n",
        "  ])\n",
        "\n",
        "loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n",
        "\n",
        "model = create_model()\n",
        "model.compile(optimizer='adam',\n",
        "              loss=loss,\n",
        "              metrics=['accuracy'],\n",
        "              steps_per_execution=10,\n",
        "              run_eagerly=True)\n",
        "\n",
        "log_dir = tempfile.mkdtemp()\n",
        "model_checkpoint = tf.keras.callbacks.ModelCheckpoint(\n",
        "    filepath=os.path.join(log_dir, 'ckpt-{epoch}'),\n",
        "    save_weights_only=True)\n",
        "\n",
        "model.fit(x=x_train,\n",
        "          y=y_train,\n",
        "          epochs=1,\n",
        "          callbacks=[model_checkpoint])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AhU3VTYZoDh-"
      },
      "source": [
        "Then, evaluate the model using `tf.keras.utils.SidecarEvaluator`. In real training, it's recommended to use a separate job to conduct the evaluation to free up worker resources for training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1VOQLDNkl2bl"
      },
      "outputs": [],
      "source": [
        "data = tf.data.Dataset.from_tensor_slices((x_test, y_test))\n",
        "data = data.batch(64)\n",
        "\n",
        "tf.keras.utils.SidecarEvaluator(\n",
        "    model=model,\n",
        "    data=data,\n",
        "    checkpoint_dir=log_dir,\n",
        "    max_evaluations=1\n",
        ").start()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rQUS8nO9FZlH"
      },
      "source": [
        "## Next steps\n",
        "\n",
        "- To learn more about sidecar evaluation consider reading the `tf.keras.utils.SidecarEvaluator` API docs.\n",
        "- To consider alternating training and evaluation in Keras consider reading about [other built-in methods](https://www.tensorflow.org/guide/keras/train_and_evaluate)."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "evaluator.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
